package utils

import (
	"crypto/md5"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/pdfcpu/pdfcpu/pkg/api"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
	"github.com/suyuan32/simple-admin-common/utils/uuidx"
)

var allowedExtensions = []string{
	".docx", ".doc", ".pdf", ".xlsx", ".pptx", ".xls", ".ppt", // 文档类型
	".jpg", ".png", ".jpeg", ".webp", // 图片类型
	".mp4", ".mov", ".mkv", // 视频类型
}

// 文件扩展名是否允许上传
func IsFileExtensionAllowed(filename string) (string, bool) {
	ext := strings.ToLower(filepath.Ext(filename)) // 获取文件扩展名并转为小写
	for _, allowedExt := range allowedExtensions {
		if ext == allowedExt {
			return ext, true
		}
	}
	return ext, false
}

// 文件Hash
func FileHash(file []byte) string {
	hashBytes := md5.Sum(file)
	return string(hashBytes[:])
}

// 文件存储路径
func FileStoragePath(ext string) string {
	timeStr := time.Now().Format("2006-01-02")
	fileUUID := uuidx.NewUUID().String()
	storeFileName := fileUUID + ext
	return fmt.Sprintf("/%s/%s/%s", ext, timeStr, storeFileName)
}

// pdf文件加锁
func PDFAes256LockFile(filePath, password string) (err error) {
	inputFile, err := os.Open(filePath)
	if err != nil {
		return err
	}

	tempFile, err := os.CreateTemp(filepath.Dir(filePath), "")
	if err != nil {
		inputFile.Close()
		return
	}
	defer func() {
		if err != nil {
			_ = inputFile.Close()
			_ = tempFile.Close()
			_ = os.Remove(tempFile.Name())
		}
		if err := tempFile.Close(); err != nil {
			return
		}
		if err := inputFile.Close(); err != nil {
			return
		}
		if err := os.Rename(tempFile.Name(), filePath); err != nil {
			return
		}
	}()

	if err = api.Encrypt(inputFile, tempFile, model.NewAESConfiguration(password, password, 256)); err != nil {
		return
	}
	return
}
